import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class CoursePanel extends JPanel {
    private JTable courseTable;
    private DefaultTableModel tableModel;
    private CourseDAO courseDAO;

    public CoursePanel() {
        courseDAO = new CourseDAO();
        setLayout(new BorderLayout(10, 10));

        // 表格
        String[] columnNames = {"课程编号", "课程名称", "学分"};
        tableModel = new DefaultTableModel(columnNames, 0);
        courseTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(courseTable);
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddDialog();
            }
        });
        buttonPanel.add(addButton);

        JButton editButton = new JButton("修改");
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = courseTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String courseId = (String) tableModel.getValueAt(selectedRow, 0);
                    showEditDialog(courseId);
                } else {
                    JOptionPane.showMessageDialog(CoursePanel.this,
                            "请先选择要修改的课程", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(editButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = courseTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String courseId = (String) tableModel.getValueAt(selectedRow, 0);
                    int option = JOptionPane.showConfirmDialog(CoursePanel.this,
                            "确定要删除课程编号为 " + courseId + " 的课程吗?", "确认删除",
                            JOptionPane.YES_NO_OPTION);
                    if (option == JOptionPane.YES_OPTION) {
                        if (courseDAO.deleteCourse(courseId)) {
                            refreshTable();
                            JOptionPane.showMessageDialog(CoursePanel.this,
                                    "删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(CoursePanel.this,
                                    "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(CoursePanel.this,
                            "请先选择要删除的课程", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(deleteButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        buttonPanel.add(refreshButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 查询面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String keyword = searchField.getText();
                if (keyword.isEmpty()) {
                    refreshTable();
                } else {
                    searchCourses(keyword);
                }
            }
        });
        searchPanel.add(new JLabel("课程编号/名称:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        add(searchPanel, BorderLayout.NORTH);

        // 初始化表格数据
        refreshTable();
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        List<Course> courses = courseDAO.getAllCourses();
        for (Course course : courses) {
            Object[] rowData = {
                    course.getCourseId(),
                    course.getCourseName(),
                    course.getCredit()
            };
            tableModel.addRow(rowData);
        }
    }

    private void searchCourses(String keyword) {
        tableModel.setRowCount(0);
        List<Course> courses = courseDAO.getAllCourses();
        for (Course course : courses) {
            if (course.getCourseId().contains(keyword) ||
                    course.getCourseName().contains(keyword)) {
                Object[] rowData = {
                        course.getCourseId(),
                        course.getCourseName(),
                        course.getCredit()
                };
                tableModel.addRow(rowData);
            }
        }
    }

    private void showAddDialog() {
        JDialog dialog = new JDialog();
        dialog.setTitle("添加课程");
        dialog.setSize(300, 200);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField creditField = new JTextField();

        panel.add(new JLabel("课程编号:"));
        panel.add(idField);
        panel.add(new JLabel("课程名称:"));
        panel.add(nameField);
        panel.add(new JLabel("学分:"));
        panel.add(creditField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Course course = new Course();
                    course.setCourseId(idField.getText());
                    course.setCourseName(nameField.getText());
                    course.setCredit(Integer.parseInt(creditField.getText()));

                    if (courseDAO.addCourse(course)) {
                        refreshTable();
                        dialog.dispose();
                        JOptionPane.showMessageDialog(CoursePanel.this,
                                "添加成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(CoursePanel.this,
                                "添加失败，课程编号可能已存在", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(CoursePanel.this,
                            "学分必须是整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showEditDialog(String courseId) {
        Course course = courseDAO.getCourseById(courseId);
        if (course == null) return;

        JDialog dialog = new JDialog();
        dialog.setTitle("修改课程信息");
        dialog.setSize(300, 200);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField(course.getCourseId());
        idField.setEditable(false);
        JTextField nameField = new JTextField(course.getCourseName());
        JTextField creditField = new JTextField(String.valueOf(course.getCredit()));

        panel.add(new JLabel("课程编号:"));
        panel.add(idField);
        panel.add(new JLabel("课程名称:"));
        panel.add(nameField);
        panel.add(new JLabel("学分:"));
        panel.add(creditField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    course.setCourseName(nameField.getText());
                    course.setCredit(Integer.parseInt(creditField.getText()));

                    if (courseDAO.updateCourse(course)) {
                        refreshTable();
                        dialog.dispose();
                        JOptionPane.showMessageDialog(CoursePanel.this,
                                "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(CoursePanel.this,
                                "修改失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(CoursePanel.this,
                            "学分必须是整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }
}
